<script setup lang="ts">
import SpecForm from "./SpecForm.vue";
import GiftBagForm from "./GiftBagForm.vue";
import type { FormInstance } from "element-plus";
import { deepClone } from "@/utils";
import { productType } from "@/config/dictionary";
import { getSpesApi, getProductDetailApi } from "@/api/activity";
import LotteryPrizeFormItem from "./components/LotteryPrizeFormItem.vue";
import BasePrizeFormItem from "./components/BasePrizeFormItem.vue";
import StockPrizeFormItem from "./components/StockPrizeFormItem.vue";
import LimitedPrizeFormItem from "./components/LimitedPrizeFormItem.vue";
import PricePrizeFormItem from "./components/PricePrizeFormItem.vue";
import { debounceUtils } from "@/utils/index.js";

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  detail: {
    type: Object,
    required: true,
  },
  title: {
    type: String,
  },
  loading: {
    type: Boolean,
    default: false,
  },
});

const emits = defineEmits(["update:modelValue", "update"]),
  currencyList: Array<any> = inject("currencyList", []),
  activityModel: string = inject("activityModel", ""),
  merchantList: any = inject("merchantList", { value: [] });

const form = ref<any>({}),
  currentSpecIndex = ref<string | number>(0),
  showSelectGoods = ref(false),
  goodsFilterParams = ref<any>({});

const formRef = ref(),
  specRef = ref<Array<any>>([]);

const initDescText=ref('')
const prizeRef=ref()
watch(
  () => props.modelValue,
  (val) => {
    if (val) {
      nextTick(async () => {
        if (formRef.value) formRef.value.resetFields();
        form.value = deepClone(props.detail);
        initDescText.value = props.detail.description||''
        nextTick(()=>{
          prizeRef.value?.clearEditor()
          prizeRef.value?.insertHTML(initDescText.value)
        })
      
        //处理商品多张图片回显
        if (props.detail.prizeType == 1 && form.value.bannerImages) {
          form.value.thumbnailUrl = form.value.bannerImages.split(",");
        }

        // 商家商品数据格式化
        if (form.value.prizeType == 1 || form.value.prizeType == 3) {
          form.value.originalPrice = Number(
            ((form.value.originalPrice || 0) / 100).toFixed(2)
          );
          form.value.prizeSpecifications.forEach(async (item: any) => {
            item.payPrice = Number(((item.payPrice || 0) / 100).toFixed(2));
          });
          currentSpecIndex.value =
            form.value.prizeSpecifications[0].uid ||
            form.value.prizeSpecifications[0].id;
        }
        // 获取商品详情
        if (form.value.prizeType == 1) {
          let detail = await getGoodsDetail(form.value.goodsId);

          form.value.goodsName = detail.productName;
          form.value.goodsType = detail.productType;
          form.value.goodsStore = detail.storeName;
        }
        // 礼品包商品
        if (form.value.prizeType == 3) {
          form.value.specStock = Infinity;
          currentSpecIndex.value =
            form.value.childPrizes && form.value.childPrizes.length > 0
              ? form.value.childPrizes[0].uid || form.value.childPrizes[0].id
              : "";
        }
        // 有默认规格商品
        if (form.value.prizeType == 2 || form.value.prizeType == 3) {
          form.value.prizeSpecifications.forEach(async (item: any) => {
            item.specStock = Infinity;
          });
        }
      });
    }
  }
);


const poolType = computed(() => {
  return form.value.poolType;
});

const validatePayPrice = (rule: any, value: any, callback: any) => {
  if (value === undefined || value === "") {
    callback(new Error("请填写现价"));
  } else {
    if (Number(value) > Number(form.value.originalPrice || 0)) {
      callback(new Error("现价不能超过原价"));
    }
    callback();
  }
};

const rules = {
  goodsId: [
    {
      required: true,
      message: "请选择积分类型",
      trigger: "change",
    },
  ],
  packNum: [{ required: true, message: "请选择礼品包类型", trigger: "change" }],
  originalPrice: [{ required: true, message: "请填写原价", trigger: "blur" }],
  // payPrice: [{ required: true, validator: validatePayPrice, trigger: "blur" }],
  // originalCurrencyNum: [{ required: true, message: "请填写积分原价", trigger: "blur" }],
  // currencyNum: [{ required: true, message: "请填写积分现价", trigger: "blur" }],
};

// 切换代币类型
const changeIntegral = (val: number) => {
  let currency = currencyList.value.find((item: any) => item.id == val);
  if (currency) {
    form.value.name = currency.name;
    form.value.thumbnailUrl = currency.logo;
    form.value.prizeSpecifications[0].name = currency.name;
    form.value.prizeSpecifications[0].thumbnailUrl = currency.logo;
  }
};

// 选择商品
const handleSelectGoods = async (row: any) => {
  let detail = await getGoodsDetail(row.productId);
  if (detail) {
    showSelectGoods.value = false;
    let uidPre = form.value.uid
      ? form.value.uid.split("-")
      : [form.value.areaId, form.value.id];
    let uid = `${uidPre[0]}-${uidPre[1]}-bag-${new Date().getTime()}`;
    form.value.childPrizes.push({
      poolType: form.value.poolType,
      prizeType: 2,
      onlineStatus: 1,
      uid: uid,
      goodsId: row.productId,
      type: detail.productType,
      goodsType: detail.productType,
      storeId: detail.storeId,
      storeName: detail.storeName,
      storePhone: detail.storePhone,
      goodsStore: detail.storeName,
      goodsName: detail.productName,
      name: detail.productName,
      thumbnailUrl: detail.img,
      originalPrice: row.originalPrice,
      bannerImages: detail.bannerImages,
      detailText: detail.detailText,
      description: detail.description,
      dir: detail.description,
      prizeSpecifications: [
        {
          type: detail.productType,
          onlineStatus: 1,
          uid: `${uidPre[0]}-${uidPre[1]}-spec-${new Date().getTime()}`,
        },
      ],
    });
    currentSpecIndex.value = uid;
  }
};

// 获取商品详情
const getGoodsDetail = async (id) => {
  const rs = await getProductDetailApi({ id });
  if (rs.code == 200) {
    return rs.payload;
  }

  return null;
};

const handleTabsAdd = () => {
  let uidPre = form.value.uid
    ? form.value.uid.split("-")
    : [form.value.areaId, form.value.id];
  // 商品规格
  if (form.value.prizeType == 1) {
    let uid = `${uidPre[0]}-${uidPre[1]}-spec-${new Date().getTime()}`;
    form.value.prizeSpecifications.push({
      type: form.value.type,
      onlineStatus: 1,
      uid: uid,
    });
    currentSpecIndex.value = uid;
  }
  // 礼品包商品
  else if (form.value.prizeType == 3) {
    showSelectGoods.value = true;
  }
};

const tabPaneRemove = (name: number | string) => {
  let index = form.value.prizeSpecifications.findIndex(
    (item: any) => item.uid == name || item.id == name
  );
  form.value.prizeSpecifications.splice(index, 1);
  currentSpecIndex.value =
    form.value.prizeSpecifications[0].uid ||
    form.value.prizeSpecifications[0].id;
};

const bagTabPaneRemove = (name: string) => {
  let index = form.value.childPrizes.findIndex(
    (item: any) => item.uid == name || item.id == name
  );
  form.value.childPrizes.splice(index, 1);
  currentSpecIndex.value =
    form.value.childPrizes.length > 0
      ? form.value.childPrizes[0].uid || form.value.childPrizes[0].id
      : "";
};

const onConfirm = () => {
  (formRef.value as FormInstance).validate(
    async (valid, invalidFields: any) => {
      if (valid) {
        let detail: any = deepClone(form.value);
        //处理商家商品多张图片
        if (detail.prizeType === 1) {
          detail.bannerImages = detail.thumbnailUrl + "";

          if (detail.thumbnailUrl instanceof Array) {
            detail.thumbnailUrl = detail.thumbnailUrl?.[0];
          } else if (detail.thumbnailUrl.includes(',')) {
            detail.thumbnailUrl = detail.thumbnailUrl.split(',')?.[0];
          } else {
            // 保留原值
            // detail.thumbnailUrl = detail.thumbnailUrl
          }
        }

        detail.originalPrice = parseInt(
          (Number(detail.originalPrice) * 100).toFixed(2).slice(0, -3)
        );
        // detail.payPrice = parseInt(
        //   (Number(detail.payPrice) * 100).toString()
        // );

        detail.areaCode = (detail.areaCode || []).join(",");
        // 校验规格
        if (
          detail.prizeType == 1 ||
          detail.prizeType == 2 ||
          detail.prizeType == 3
        ) {
          let prizeSpecifications =
            detail.prizeType == 3
              ? detail.childPrizes
              : detail.prizeSpecifications;
          // 规格校验

          for (let i = 0; i < prizeSpecifications.length; i++) {
            // 单位为分,需要*100
            prizeSpecifications[i].payPrice = parseInt(
              (Number(prizeSpecifications[i].payPrice) * 100).toFixed(2).slice(0, -3)
            );
            if (detail.prizeType == 1 || detail.prizeType == 3) {
              if (form.value.id === undefined) {
                prizeSpecifications[i] = await specRef.value[i].check();
              }
              if (activityModel !== "edit") {
                try {
                  prizeSpecifications[i] = await specRef.value[i].check();
                } catch (e) {
                  currentSpecIndex.value =
                    prizeSpecifications[i].id || prizeSpecifications[i].uid;
                  return;
                }
              }
            }
          }

          // 计算库存
          detail.stock = detail.prizeSpecifications.reduce(
            (total: number, item: any) => {
              if (item.onlineStatus == 0) return total;
              return total + item.stock;
            },
            0
          );
          detail.stockTotal = detail.prizeSpecifications.reduce(
            (total: number, item: any) => {
              if (item.onlineStatus == 0) return total;
              return total + item.totalStock;
            },
            0
          );
          // 礼品包
          if (detail.prizeType == 3) {
            if (!detail.childPrizes || detail.childPrizes.length == 0) {
              ElNotification.error({
                message: "还未配置商品",
              });
              return;
            }
            let stock = detail.childPrizes.reduce(
              (total: number, item: any) => {
                if (item.onlineStatus == 0) return total;
                return total + item.prizeSpecifications[0].stock;
              },
              0
            );
            if (detail.packNum == 1 && stock < detail.stockTotal) {
              ElNotification.error({
                message: "各商品的库存之和应大于等于礼品包库存",
              });
              return;
            }

            detail.prizeSpecifications[0].payPrice = Number(
              (Number(detail.prizeSpecifications[0].payPrice) * 100).toFixed(2).slice(0, -3)
            );

            detail.prizeSpecifications[0].name = detail.name;
            detail.prizeSpecifications[0].thumbnailUrl = detail.thumbnailUrl;
          }

          if (detail.prizeType == 2) {
            detail.name = detail.prizeSpecifications[0].name;
            detail.thumbnailUrl = detail.prizeSpecifications[0].thumbnailUrl;
          }

          detail.description = detail.dir;
        }
        emits("update", deepClone(detail));
      } else {
        formRef.value.scrollToField(Object.keys(invalidFields)[0]);
      }
    }
  );
};

const onClose = () => {
  emits("update:modelValue", false);
};
const handleTextChange=({ innerHTML }: { innerHTML: string })=>{
  form.value.dir=innerHTML
}
const tableParmas=ref<any>({
  defaultStore: 0,
    minCost:null,
    maxCost:null
})

const rulesCost={
  minAmount:[{
      trigger:'blur',
      validator:(rule,value,callback)=>{
        if(value){
          if(!/^(([1-9]\d*)|(0{1}))(\.\d{1,2})?$/.test(value)){
            callback('请输入正确格式,保留两位小数!')
          }else if(+value>9999999999){
            callback('超过上限【99,9999,9999】')
          }else if(goodsFilterParams.value.maxCost&&+value>goodsFilterParams.value.maxCost){
            callback('请输入正确的范围!')
          }else{
            callback()
          }
        }else{
          callback()
        }
      }
    }
  ],
  maxAmount:[{
      trigger:'blur',
      validator:(rule,value,callback)=>{
        if(value){
          if(!/^(([1-9]\d*)|(0{1}))(\.\d{1,2})?$/.test(value)){
            callback('请输入正确格式,保留两位小数!')
          }else if(+value>9999999999){
            callback('超过上限【99,9999,9999】')
          }else if(goodsFilterParams.value.minCost&&+value<goodsFilterParams.value.minCost){
            callback('请输入正确的范围!')
          }else{
            callback()
          }
        }else{
          callback()
        }
      }
    }]
}
const searchList=debounceUtils(()=>{
  SelectGoodsRef.value.search()
},800)
const SelectGoodsRef=ref()
const goodsFilterParamsRef=ref()
watch(goodsFilterParams,()=>{
  goodsFilterParamsRef.value?.validate((valid:boolean)=>{
    if(valid){
      tableParmas.value={...goodsFilterParams.value}
      tableParmas.value.minCost=goodsFilterParams.value.minCost?(goodsFilterParams.value.minCost)*100:null
      tableParmas.value.maxCost=goodsFilterParams.value.maxCost?(goodsFilterParams.value.maxCost)*100:null
      searchList()
    }
  })
},{deep:true})
watch(showSelectGoods,(val)=>{
  if(!val){
    goodsFilterParamsRef.value?.resetFields()
  }
})

provide("formRef", formRef);
</script>
<template>
  <Dialog :model-value="modelValue" :title="title" :loading="loading" close-on-click-modal @confirm="onConfirm" @opened="openHandle"
    @close="onClose">
    <el-form ref="formRef" :model="form" :rules="rules" label-width="auto">
      <h3 class="collpase-title" v-if="form.prizeType != 0">
        {{ form.prizeType === 3 ? "礼品包信息" : "商品信息" }}
      </h3>
      <!-- 商品属性 -->
      <!-- <div class="product-info" v-if="form.prizeType == 1">
        <span>商品名称：{{ form.goodsName }}</span>
        <span>商品类型：{{ productType[form.goodsType] }}</span>
        <span>所属商家：{{ form.goodsStore }}</span>
      </div> -->
      <!-- 商品、谢谢参与、礼品包 -->
      <BasePrizeFormItem :isAddFirstText="form.prizeType == 1" :pictureNumber="form.prizeType == 1 ? 10 : 1"
        v-if="form.prizeType == 0 || form.prizeType == 1 || form.prizeType == 3" :label="form.prizeType == 3
          ? ['礼品包名称', '礼品包图片']
          : ['奖品名称', '奖品图片']
          " v-model="form" />
      <!-- 积分 -->
      <template v-if="form.prizeType == 2">
        <el-form-item label="积分类型:" prop="goodsId">
          <el-select v-model="form.goodsId" placeholder="请选择" @change="changeIntegral">
            <el-option v-for="(item, key) in currencyList" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <template v-for="(spec, index) in form.prizeSpecifications">
          <el-form-item label="积分数量:" :prop="`prizeSpecifications.${index}.rewardGoodsNum`" :rules="[
            { required: true, message: '请输入积分数量', trigger: 'blur' },
          ]">
            <EasyNumberInput v-model="spec.rewardGoodsNum" :min="0" unit="个" :precision="0" />
          </el-form-item>
          <BasePrizeFormItem v-model="form.prizeSpecifications[index]" :label="['积分名称', '积分图片']"
            :prefix="`prizeSpecifications.${index}.`" />
          <StockPrizeFormItem v-if="activityModel !== 'edit' || form.id === undefined"
            v-model="form.prizeSpecifications[index]" :prefix="`prizeSpecifications.${index}.`" />
        </template>
        <!-- 限制条件 -->
        <LimitedPrizeFormItem v-model="form" :poolType="poolType" :type="form.type" />
      </template>
      <!-- 礼品包 -->
      <template v-if="form.prizeType == 3">
        <el-form-item required label="礼品包类型:" prop="packNum">
          <el-radio-group v-model="form.packNum">
            <el-radio :label="-1">全选</el-radio>
            <el-radio :label="1">任选其一</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="原价" prop="originalPrice">
          <EasyNumberInput v-model="form.originalPrice" />
        </el-form-item>
        <template v-for="(spec, index) in form.prizeSpecifications">
          <!-- 现价 -->
          <PricePrizeFormItem v-model="form.prizeSpecifications[index]" :prefix="`prizeSpecifications.${index}.`" />
          <StockPrizeFormItem v-if="activityModel !== 'edit' || form.id === undefined"
            v-model="form.prizeSpecifications[index]" :prefix="`prizeSpecifications.${index}.`" />
        </template>
        <LimitedPrizeFormItem v-model="form" :poolType="poolType" :type="form.type" />
      </template>
      <!-- 抽奖特有属性 -->
      <LotteryPrizeFormItem v-if="poolType == 1" v-model="form" />
      <el-form-item v-if="activityModel !== 'edit' || form.id === undefined" label="状态:" prop="onlineStatus">
        <el-switch v-model="form.onlineStatus" inline-prompt active-text="上架" inactive-text="下架" :active-value="1"
          :inactive-value="0" />
      </el-form-item>
      <!-- 商品属性 -->
      <template v-if="form.prizeType == 1">
        <el-form-item prop="auditStatus">
          <template #label>
            <div class="audit-label"><span>商品审核</span>
              <el-popover placement="bottom" :width="200" trigger="hover"
                content="开启后，用户兑换该商品，需要经过您的审核，审核通过的用户可以领取，审核拒绝则领取失败">
                <template #reference>
                  <span class="question-icon">?</span>
                </template>
              </el-popover>
            </div>
          </template>
          <div> <el-switch active-text="开启" inactive-text="关闭" inline-prompt v-model="form.verifyFlag" :active-value="1"
              :inactive-value="0" />
            <div class="tips">开启后,及时前往“订单管理-审核订单”进行审核</div>
          </div>
        </el-form-item>
        <el-form-item label="市场价:" prop="originalPrice">
          <EasyNumberInput v-model="form.originalPrice" />
        </el-form-item>
        <RechargeName v-if="form.type == 'recharge'" v-model:model-value="form.rechargeAccountRegexId"
          v-model:model-regx="form.rechargeAccountRegex" v-model:model-place-holder="form.rechargePlaceHolder" />
        <!-- 商品规格属性 -->
        <template v-if="activityModel !== 'edit' || form.id === undefined">
          <div class="tabs-add" v-if="poolType == 2">
            <el-button type="primary" icon="plus" @click="handleTabsAdd">添加规格</el-button>
          </div>
          <el-tabs v-model="currentSpecIndex" type="card" class="demo-tabs" @tab-remove="tabPaneRemove">
            <el-tab-pane v-for="(spec, index) in form.prizeSpecifications" :label="spec.name || `规格-${index}`"
              :name="spec.uid || spec.id" :closable="poolType == 2 && form.prizeSpecifications.length > 1">
              <SpecForm :ref="(el) => {
                if (el) specRef[index] = el;
              }
                " v-model="form.prizeSpecifications[index]" :poolType="poolType" :goodsId="form.goodsId" />
            </el-tab-pane>
          </el-tabs>
        </template>
        <!-- 限制条件 -->
        <LimitedPrizeFormItem v-model="form" :poolType="poolType" :type="form.type" />
      </template>
      <!-- 礼品包属性 -->
      <template v-if="form.prizeType == 3 &&
        (activityModel !== 'edit' || form.id === undefined)
        ">
        <h3 class="collpase-title">
          商品与库存
          <div class="tabs-add">
            <el-button type="primary" icon="plus" @click="handleTabsAdd">添加商品</el-button>
          </div>
        </h3>
        <!-- 商品规格属性 -->
        <el-tabs v-model="currentSpecIndex" type="card" @tab-remove="bagTabPaneRemove">
          <el-tab-pane v-for="(prize, index) in form.childPrizes" :key="prize.uid" :label="prize.name || `商品-${index}`"
            :name="prize.uid || prize.id" closable>
            <GiftBagForm :ref="(el) => {
              if (el) specRef[index] = el;
            }
              " v-model="form.childPrizes[index]" :poolType="poolType" :stock="form.prizeSpecifications[0].stock"
              :grantType="form.packNum" />
          </el-tab-pane>
        </el-tabs>
      </template>
      <template v-if="form.prizeType == 2 || form.prizeType == 3">
        <h3 class="collpase-title">使用说明</h3>
        <el-form-item label="使用说明:" prop="dir">
          <!-- <el-input v-model="form.dir" :autosize="{ minRows: 4 }" maxlength="500" show-word-limit type="textarea"
            placeholder="请填写使用说明" /> -->
            <rich-editor :id-name="`prize-${props.detail.id}`" :initial-value="initDescText" @change="handleTextChange" ref="prizeRef"></rich-editor>
        </el-form-item>
      </template>
    </el-form>
  </Dialog>
  <!-- 选择商品类型 -->
  <SelectGoods v-model:show="showSelectGoods" tableUrl="activity/ext/getProductList" :table-param="tableParmas"  ref="SelectGoodsRef"
    stock="allStock" @select="handleSelectGoods">
    <template #search>
      <el-tabs v-model="goodsFilterParams.defaultStore" class="demo-tabs">
        <el-tab-pane name="0" label="商户商家供货" />
        <el-tab-pane name="1" label="联海供货" />
      </el-tabs>
      <!-- <search-bar inline>
        <template #normal> -->
          <el-form :model="goodsFilterParams" inline ref="goodsFilterParamsRef">
            <el-form-item label="商品类型">
              <el-select v-model="goodsFilterParams.productType" placeholder="请选择商品类型">
                <el-option v-for="(item, key) in productType" :label="item" :value="key" />
              </el-select>
            </el-form-item>
            <el-form-item label="商家">
              <el-select v-model="goodsFilterParams.storeId" placeholder="请选择商家">
                <el-option v-for="(item, key) in merchantList" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item class="input-range-box">
              <el-form-item label="供货价" style="margin-right:12px" label-width="68px" 
              prop="minCost" :rules="rulesCost.minAmount">
                <el-input  style="width: 200px;" v-model="goodsFilterParams.minCost" placeholder="请输入最低金额" clearable></el-input>
              </el-form-item>
              <el-form-item  prop="maxCost" :rules="rulesCost.maxAmount">
                <template #label>
                  <span>~</span>
                </template>
                <el-input style="width: 200px;" v-model="goodsFilterParams.maxCost" placeholder="请输入最高金额" clearable></el-input>
              </el-form-item>
            </el-form-item>
          </el-form>
        <!-- </template>
      </search-bar> -->
    </template>
  </SelectGoods>
</template>
<style lang="scss" scoped>
.product-info {
  margin-bottom: 20px;

  span {
    +span {
      margin-left: 20px;
    }
  }
}

.tabs-add {
  float: right;
  position: relative;
  z-index: 1;
}

:deep(.el-tabs) {
  .el-tabs__header {
    margin-bottom: 0;

    .el-tabs__item {
      &.is-active {
        background-color: #f4f5f9;
      }
    }
  }

  .el-tabs__content {
    padding-top: 24px;
    background-color: #f4f5f9;
    border-bottom-left-radius: 15px;
    border-bottom-right-radius: 15px;
    width: 100%;
  }
}

.collpase-title {
  position: relative;
  padding-left: 10px;
  font-size: 16px;
  margin-bottom: 10px;

  &::before {
    content: "";
    display: block;
    width: 3px;
    height: 16px;
    border-radius: 2px;
    background-color: var(--el-color-primary);
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
  }

  span {
    font-size: 13px;
    color: #909399;
    margin-left: 10px;
    font-weight: normal;
  }
}

.audit-label {
  display: flex;
  align-items: center;
}

.question-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 12px;
  height: 12px;
  margin-left: 4px;
  font-size: 10px;
  color: var(--el-text-color-regular);
  border-radius: 50%;
  border: 1px solid var(--el-text-color-regular);
}

.tips {
  font-size: 12px;
  color: #999;
}
</style>
